package com.begye.smartloan.apptest.fangkui

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.begye.smartloan.apptest.MyApplication
import com.begye.smartloan.apptest.tool.IApiProcessCallback
import com.begye.smartloan.apptest.tool.doImageUpload
import com.begye.smartloan.apptest.tool.doPostRequest
import com.util.utillib.util.imagecovert.ImageConvert
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

class FangKuiViewModel : ViewModel() {

    var type: String = ""
    var imageList = mutableListOf<JSONObject>()

    private val _loadingStateLiveData = MutableLiveData<Boolean>()
    val onLoadingStateLiveData get() = _loadingStateLiveData

    private val _saveFangKuiSuccessLiveData = MutableLiveData<Boolean>()
    val onSaveFangKuiSuccessLiveData get() = _saveFangKuiSuccessLiveData


    fun initImageList() {
        imageList.clear()
        val obj = JSONObject().apply {
            put("isAdd", "YES")
        }
        imageList.add(obj)
    }

    fun imageListRemove(index: Int) {
        if (index in imageList.indices) {
            imageList.removeAt(index)
        }

        if (imageList.isEmpty()) {
            initImageList()
            return
        }

        val firstItemIsAdd = imageList.firstOrNull()?.optString("isAdd") == "YES"
        if (!firstItemIsAdd) {
            imageList.add(0, JSONObject().apply {
                put("isAdd", "YES")
            })
        }
    }


    fun isMaxImages(): Boolean {
        return imageList.size >= 3
    }

    fun handleTakePictureResult(
        result: String?,
        onConversionCompleted: (Int, Bitmap?, Int) -> Unit,
        onUploadCompleted: (Int, String?, Int) -> Unit
    ) {
        try {
            println(result.toString())

            result?.let {
                val localPath = it
//                val thumpImg = imagePathToBitmap(localPath)

                val obj = JSONObject().apply {
                    put("isAdd", "NO")
                    put("path", localPath)
                }
                imageList.add(obj)
                if (imageList.size >= 4) {
                    imageList.removeFirst()
                }
                onConversionCompleted.invoke(0, null, 0)
                requestUploadImage(localPath, 0, 0, onUploadCompleted)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    @SuppressLint("Recycle")
    fun handlePhotoAlbumResult(
        context: Context,
        result: Uri?,
        onConversionCompleted: (Int, Bitmap?, Int) -> Unit,
        onUploadCompleted: (Int, String?, Int) -> Unit
    ) {
        try {
            println(result.toString())
            result?.let {
                val path = imageUriToLocalFile(context, it)
                //压缩图片
                ImageConvert.startConvertImage(context, File(path)) { localPath, thumpImg ->
                    val obj = JSONObject().apply {
                        put("isAdd", "NO")
                        put("path", localPath)
                    }
                    imageList.add(obj)
                    if (imageList.size >= 4) {
                        imageList.removeFirst()
                    }
                    onConversionCompleted.invoke(0, thumpImg, 0)
                    localPath?.let {
                        requestUploadImage(
                            localPath,
                            0,
                            0,
                            onUploadCompleted
                        )
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    private fun imageUriToLocalFile(
        context: Context,
        contentURI: Uri
    ): String {
        try {
            println(contentURI.path)

            val imgDir = "${context.filesDir}${File.separator}${MyApplication.product}_TEMP_PICS"
            val dirFile = File(imgDir)
            if (!dirFile.exists()) {
                dirFile.mkdirs()
            }

            val outFilePath = "$imgDir${File.separator}${System.currentTimeMillis()}.jpg"
            val imgInputStream: InputStream =
                context.contentResolver.openInputStream(contentURI) ?: return ""
            val outFile = File(outFilePath)
            val buffer = ByteArray(1024)
            var len: Int
            val fos = FileOutputStream(outFile)
            while (imgInputStream.read(buffer).also { len = it } != -1) {
                fos.write(buffer, 0, len)
            }
            fos.flush()
            fos.close()
            imgInputStream.close()
            return outFilePath
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    private fun imagePathToBitmap(filePath: String?): Bitmap {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = false
        return BitmapFactory.decodeFile(filePath, options)
    }

    fun canSubmit(input: String): Boolean {
        return !(type.isBlank() or input.isBlank())
    }

    fun requestSaveFangKui(input: String) {
        val params = hashMapOf<String, Any>()
        params["type"] = type
        params["opinion"] = input

        val urlList = mutableListOf<String>()
        for (element in imageList) {
            val url = element.optString("url", "")
            if (url.isNotBlank()) {
                urlList.add(url)
            }
        }
        if (urlList.isNotEmpty()) {
            params["images"] = urlList.joinToString(",")
        }

        doPostRequest(
            path = "f7onKyHCqrxf6HniaI2ECA",
            action = params,
            loading = _loadingStateLiveData,
            callback = object : IApiProcessCallback {
                override fun onApiReady() {
                }

                override fun onApiDone(jsonObject: JSONObject) {
                    _saveFangKuiSuccessLiveData.value = true
                }

                override fun onApiError(code: String, errMsg: String) {
                    _saveFangKuiSuccessLiveData.value = false
                }
            })
    }

    private fun requestUploadImage(
        filePath: String,
        type: Int,
        position: Int,
        onFinished: (Int, String?, Int) -> Unit
    ) {
        doImageUpload(
            filePath = filePath,
            loading = _loadingStateLiveData,
            callback = object : IApiProcessCallback {
                override fun onApiReady() {
                }

                override fun onApiDone(jsonObject: JSONObject) {
                    val url = jsonObject.optString("url", "")
                    if (url.isNotBlank()) {
                        if (imageList.size > 1) {
                            imageList.last().apply {
                                put("url", url)
                            }
                        }
                        onFinished.invoke(type, url, position)

                    } else {
                        if (imageList.size >= 3) {
                            imageList.removeLast()
                            imageList.add(0, JSONObject().apply {
                                put("isAdd", "YES")
                            })
                        } else {
                            if (imageList.size > 1) {
                                imageList.removeLast()
                            } else {
                                initImageList()
                            }
                        }
                        onFinished.invoke(type, null, position)
                    }
                }

                override fun onApiError(code: String, errMsg: String) {
                    if (imageList.size >= 3) {
                        imageList.removeLast()
                        imageList.add(0, JSONObject().apply {
                            put("isAdd", "YES")
                        })
                    } else {
                        if (imageList.size > 1) {
                            imageList.removeLast()
                        } else {
                            initImageList()
                        }
                    }
                    onFinished.invoke(type, null, position)
                }
            })
    }

}